import re
import time
from azure.cognitiveservices.speech.audio import  PushAudioOutputStream, PushAudioOutputStreamCallback
from api_audio import AudioPlay
from send_micro_weight import send_azure_blendshape_weight2
from sound_animation import SoundAnimation

def online_run_message(play_content):
    '''
    例子：online_run_message("愿你眼眸有希望，心中有大海。每一岁都奔走在自己的热爱里。所有的一切都渐入佳境，既要今朝醉。")
    :param play_content:
    :return:
    '''
    audio_stream_list = []
    weight_list = []
    class MyHandle(PushAudioOutputStreamCallback):

        def write(self, audio_buffer: memoryview) -> int:
            audio_stream_list.append(audio_buffer.tobytes())
            return 0
    def get_azure_sound_weights(evt):
        if evt.animation:
            weight_list.append(evt.animation)
        pass

    from azure.cognitiveservices.speech.audio import AudioOutputConfig
    import azure.cognitiveservices.speech as speechsdk

    speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)

    speech_config.speech_synthesis_language = "zh-CN"
    speech_config.speech_synthesis_voice_name ="zh-CN-XiaoyouNeural"


    audiooutputstream = PushAudioOutputStream(MyHandle())
    audio_config = AudioOutputConfig(stream=audiooutputstream)

    speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)


    speech_synthesizer.viseme_received.connect(get_azure_sound_weights)
    ssml = '''<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis"
           xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="zh-CN">
        <voice name="zh-CN-YunzeNeural">
            <mstts:viseme type="FacialExpression"/>
            <mstts:express-as style="calm" styledegree="1">
                %s
            </mstts:express-as>
        </voice>
    </speak>'''% play_content
    # If VisemeID is the only thing you want, you can also use `speak_text_async()`
    start_time = time.time()
    print("begin")
    result = speech_synthesizer.speak_ssml_async(ssml).get()
    time2 = time.time()
    print("end1",time2-start_time)
    sound_animation.put_data(weight_list,audio_stream_list)
    print("end2",time.time()-time2)
fi = None
def generate_audio_and_blendshapes():
    fi = open('blendshape.txt', 'w', encoding='utf8')
    def save_azure_sound_weights(evt):
        animation = evt.animation
        if animation:
            print(animation)
            fi.write(animation)
            fi.write('\n')
            fi.flush()

    from azure.cognitiveservices.speech.audio import AudioOutputConfig
    import azure.cognitiveservices.speech as speechsdk
    speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)

    speech_config.speech_synthesis_language = "zh-CN"
    speech_config.speech_synthesis_voice_name = "zh-CN-XiaoyouNeural"

    audio_config = AudioOutputConfig(filename="file2.wav")

    speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)

    speech_synthesizer.viseme_received.connect(save_azure_sound_weights)
    ssml = '''<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis"
               xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="zh-CN">
            <voice name="zh-CN-YunzeNeural">
                <mstts:viseme type="FacialExpression"/>
                <mstts:express-as style="calm" styledegree="1">
                    愿你眼眸有星辰。心中有大海。每一岁都奔走在自己的热爱里。所有的一切都渐入佳境，既要今朝醉。也要万年长! 你的新年好运正在派件。请保持好心情。
    新的一年。愿一切困难都能避重就轻。每一次困难都有心中共鸣。山野皆有雾灯。飘摇亦可归舟。所遇皆良善。所行化坦途。
                </mstts:express-as>
            </voice>
        </speak>'''
    # If VisemeID is the only thing you want, you can also use `speak_text_async()`
    global start_time
    start_time = time.time() + 2
    result = speech_synthesizer.speak_ssml_async(ssml).get()

def outline_run_message():
    player = AudioPlay()
    player.play_wav_file_thread(filename="file2.wav")
    fr = open('blendshape.txt', 'r', encoding='utf8')
    start_time = time.time()
    for each in fr:
        send_azure_blendshape_weight2(each,start_time)

if __name__ == '__main__':
    speech_key, service_region = "key", "eastus"
    sound_animation = SoundAnimation()
    read_message = '''
    说到软文，大部分人的感觉都是反感的，觉得这不是什么好东西，是一种带有欺骗色彩的商业文案，是一种糖衣炮弹。如果你有这样的认识，我并不会怪你，因为确实有这样的一些软文，它们的套路明显，文笔拙劣，动机不纯，很难不让人产生这种负面的映像。但作为一名软文写手，我不得不说的是，你看到的这类软文仅仅是众多软文中的一部分，而且绝对不是最好的那一部分。最好的那部分软文，你可能已经读过很多遍，甚至已经背下来了，作者也可能都告诉你这是软文了，但你却从没有意识到那是软文。
    '''
    total_each = ""
    split_message = re.split(r'([，。；！？：])', read_message)
    for i,each in enumerate(split_message):
        if each:
            print(total_each)
            total_each += each
            if len(total_each)>30 or i == len(split_message)-1:
                if i == len(split_message)-1:
                    online_run_message(total_each)
                    total_each = ""
                else:
                    if total_each[-1]  in "，。；！？：":
                        online_run_message(total_each)
                        total_each = ""
    print("run end")



